package room_event

import (
	"fmt"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/api"
	cache3 "longmen/server/internal/rpc/tencentim/cache"
	"longmen/server/internal/rpc/tencentim/chat"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/pvt_chat"
	utils2 "longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/internal/services/consumers/publisher"
	"longmen/server/internal/services/nami/utils"
	cache2 "longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"

	"github.com/spf13/cast"
)

func GetMatchData(usr *chat.ClientUser) (*messages2.RoomMatchData, error) {

	roomCfg, err := cache3.GetLiveConfig(usr.RoomId)
	if err != nil {
		return nil, err
	}
	if roomCfg.Matchid < 1 {
		return nil, fmt.Errorf("主播没有直播赛事")
	}

	result, err := api.GetAPI().GetMatchData(usr.RoomId)
	if err != nil {
		return nil, err
	}

	md := &messages2.RoomMatchData{}
	md.MatchId = result.Id
	md.HomeScore = result.HomeScore
	md.AwayScore = result.AwayScore
	md.Time = fmt.Sprintf("%s---%v", result.Status, utils2.FormTime(int(result.Time)))
	md.HomeName = result.HomeName
	md.AwayName = result.AwayName
	t := time.Unix(result.KickoffTime, 0)
	md.KickoffTime = t.Format("2006/01/02 15:04:05")
	md.HomeLogo = result.HomeLogo
	md.AwayLogo = result.AwayLogo
	md.EventName = result.CompetitionName

	return md, nil
}

func handlingLogin(req *pb.CallbackReq, usr *chat.ClientUser) (ret *pb.CallbackResp, err error) {
	defer func() {
		//crontab.ReplayChatClientHub.EnterReplayRoom(usr.RoomId, usr.UserId)
	}()

	// 不管是否加入成功，先计算是个活跃用户
	rep := &messages2.LoginReplyMessage{}
	user, err := cache2.GetUserFullInfo(usr.UserId)

	//global.Log.Debugf("IncrIpStats handlingLogin 渠道ID:%+v", usr.SourceKey)

	if err != nil {
		return utils2.CallbackOkAndExt(rep, cast.ToString(usr.RoomId)), err
	}

	// 渠道统计
	if len(user.RegSourceId) <= 0 {
		user.RegSourceId = usr.SourceKey
	}
	if len(user.RegSourceId) > 0 {
		err = global.PublishChannelStats.Send(publisher.ActiveChannelStats, user)
		if err != nil {
			global.Log.Errorf("Nats publish chanel %s", err.Error())
		}
	}

	// 绑定用户信息到客户端

	rep.Type = messages2.LoginReplyMessageType

	rep.Message = "loginRep"

	rep.User = &messages2.LoginReplyMessageUserInfo{
		Platform:   usr.Platform,
		UserId:     usr.UserId,
		RoomId:     usr.RoomId,
		ClientName: usr.ClientName,
		Avatar:     usr.Avatar,
		Level:      usr.Level,
		Vip:        usr.Vip,
		Role:       usr.Role,
		Permit:     usr.Permit,
		Anonymouse: usr.Anonymouse,
		Props:      usr.Props,
		ImmeGift:   usr.ImmeGift,
	}
	rep.Data = &messages2.LoginReplyMessageData{}
	rep.Data.Guess = cache2.GetLastGuessStatusMsgForRoom(usr.RoomId)
	rep.Data.ChatHistory = GetChatHistory(usr.RoomId).GetChatHistory()
	rep.Data.Role = usr.Role
	rep.Data.Permit = usr.Permit

	//global.Log.Debugf("房间id是:%v|聊天记录:%v|rep:%v", usr.RoomId, rep.Data.ChatHistory, rep.User)
	// 填充在线用户列表
	count := 0

	//count := room.NumberOfClients()
	//取得房间 AnchorName
	configPub := cache2.GetConfigPub()
	rep.Data.Message = configPub.ChatSysMessage
	rep.Data.OnlineNum = count
	//if !cache.RepeatedIPJoin(usr.RoomId, usr.IP) {

	cache3.PushLoginInfo(usr, false)
	//} else {
	//global.Log.Infof("repeated IP:%s", usr.IP)
	//}
	//global.Log.Debugf("返回登录消息:%+v", rep.Data.ChatHistory)
	anchor, err := cache2.GetUserFullInfo(usr.RoomId) //房间有可能是官方直播
	if err == nil && anchor.Id > 0 {
		cache3.SetEntryExitTimes(usr, "login")
		pvt_chat.NewOnlineDevice().WriteToRedis(pvt_chat.OnlineDeviceRequest{
			DeviceId:       cast.ToString(usr.UserId),
			Platform:       usr.Platform,
			UserID:         cast.ToString(usr.UserId),
			Nickname:       usr.ClientName,
			UserLevel:      usr.Level,
			RoomID:         usr.RoomId,
			LastOnlineTime: time.Now().Unix(),
		})
		conversation, err := pvt_chat.GetSingleChatConversationSendIdToRecvId(cast.ToString(usr.RoomId), cast.ToString(usr.UserId))
		if err == nil && conversation != nil {
			//cache3.RoomUserOnline(usr.RoomId, usr.UserId) // 更新 cache - 加入 房间
		}
	}

	IncrIpStats(usr.RoomId, usr.IP)
	//cache3.IncGlobalLiveRoomIp(usr.IP) 改到livePageData接口统计
	utils.SafeGo(func() {
		setTimUserNick(req.From_Account, usr.ClientName)
	})
	return utils2.CallbackOkAndExt(rep, cast.ToString(usr.RoomId)), nil
}
